package com.huaao.micropolice.core.repository;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.huaao.micropolice.core.common.page.Page;
import com.huaao.micropolice.core.common.page.Parameter;
import com.huaao.micropolice.core.common.page.Sort;

@Repository
public class BaseDao{
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession(){
		if(sessionFactory.getCurrentSession()==null){
			return sessionFactory.openSession();
		}
		return sessionFactory.getCurrentSession();
	}
	
	/**
	 * 保存对象不返回 数据库id
	 * @param obj
	 */
	public void persist(Object obj){
		getSession().persist(obj);
	}
	
	/**
	 * 保存实体,返回id
	 * 
	 * @param obj 实体对象
	 * @return id
	 */
	public String save(Object obj){
		return (String) getSession().save(obj);
	}
	
	/**
	 * 修改实体
	 * 
	 * @param obj 实体对象
	 *            
	 */
	public void update(Object obj){
		getSession().merge(obj);
	}
	
	public Object load(Class clazz , Serializable id){
		return getSession().load(clazz, id);
	}
	
	public Object get(Class clazz , Serializable id){
		return getSession().get(clazz, id);
	}
	
	/**
	 * 删除实体
	 * 
	 * @param obj 实体对象
	 *            
	 */
	public void delete(Object obj) {
		getSession().delete(obj);
	}
	
	/**
	 * 根据ID删除实体类
	 * 
	 * @param clazz 实体类class
	 *            
	 * @param id 主键
	 *            
	 */
	public void deleteById(Class clazz, Serializable id) {
		Object entity = load(clazz, id);
		delete(entity);
	}
	
	@SuppressWarnings("unchecked")
	public List findByPage(Class clazz,List<Parameter> params,Sort sort,Page page){
		if(sort==null){
			sort=new Sort();
		}
		String hql = getHql(clazz,params, sort);
		Query query = getSession().createQuery(hql);
		List list = null;
		if(page!=null){
			page.setTotalCount(getCount(hql));
			query.setFirstResult(page.getFirst()).setMaxResults(page.getPageSize());
			list = query.list();
			page.setResults(list);
		}
		return list;
	}
		
	public String getHql(Class clazz,List<Parameter> params,Sort sort){
		StringBuffer buffer=new StringBuffer("From "+clazz.getSimpleName()+" where 1=1");
		if(params!=null&&params.size()>0){
			for(Parameter p:params){
				buffer.append(p.getHql());
			}
		}
		if(sort==null){
			sort=new Sort();
		}
		buffer.append(" order by "+sort.getName() + " " +sort.getType());
		return buffer.toString();
	}
	
	@SuppressWarnings("unchecked")
	public Long getCount(String hql){
		Query query = getSession().createQuery("select count(*) "+hql);
		List list= query.list();
		return (list!=null&&list.size()>0)?(Long)list.get(0):0;
	}
}
